package com.tuoren.forward.service;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tuoren.forward.entity.Role;
import com.tuoren.forward.entity.RolePermission;
import com.tuoren.forward.entity.req.RoleAuthReq;
import com.tuoren.forward.entity.req.RoleSearchReq;
import com.tuoren.forward.mapper.RoleMapper;
import com.tuoren.forward.mapper.RolePermissionMapper;
import com.tuoren.forward.util.Result;
import com.tuoren.forward.util.ResultData;
import com.tuoren.forward.util.ResultPage;

@Service
public class RoleService {
	
	@Autowired
	RoleMapper roleMapper;
	
	@Autowired
	RolePermissionMapper rolePermissionMapper;
	
	/**
	 * @title 查询角色
	 * @param req
	 * @return
	 */
	public ResultPage<Role> search(RoleSearchReq req){
		Page<Object> page = PageHelper.startPage(req.getPage(), req.getSize());
		Role role = new Role();
		BeanUtils.copyProperties(req, role);
		List<Role> roles = roleMapper.select(role);
		ResultPage<Role> result = ResultPage.success(roles, page.getTotal());
		return result;
	}
	
	/**
	 * @title 列出所有角色
	 * @param req
	 * @return ResultData<List<Role>>
	 */
	public ResultData<List<Role>> listAll(){
		List<Role> roles = roleMapper.selectAll();
		return ResultData.success(roles);
	}
	
	/**
	 * @title 添加角色
	 * @param req
	 * @return
	 */
	public Result add(Role req) {
		Role exist = roleMapper.selectByPrimaryKey(req.getId());
		if(exist != null) {
			return Result.fail("角色已存在");
		}
		roleMapper.insert(req);
		return Result.success();
	}
	
	/**
	 * @title 修改角色
	 * @param req
	 * @return
	 */
	public Result edit(Role req) {
		// TODO Auto-generated method stub
		roleMapper.updateByPrimaryKeySelective(req);
		return Result.success();
	}
	
	@Transactional(rollbackFor = Exception.class)
	public Result delete(String id) {
		// TODO Auto-generated method stub
		roleMapper.deleteByPrimaryKey(id);
		rolePermissionMapper.deleteByRoleId(id);
		return Result.success();
	}
	
	@Transactional
	public Result authPermission(RoleAuthReq req) {
		rolePermissionMapper.deleteByRoleId(req.getRoleId());
		if(req.getPermissionIds() != null) {
			RolePermission roleP = new RolePermission();
			roleP.setRoleId(req.getRoleId());
			for(Integer pid : req.getPermissionIds()) {
				roleP.setPermissionId(pid);
				rolePermissionMapper.insert(roleP);
			}
		}
		return Result.success();
	}
}
